﻿using AutoMapper;
using MediatR;
using ProduceBasicData.Api.Application.Command.DeviceManage;
using ProduceBasicData.Domain.DeviceManage;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.DeviceManage
{
    /// <summary>
    /// 批量删除设备类型命令处理器
    /// </summary>
    /// <remarks>
    /// 构造函数
    /// </remarks>
    /// <param name="deviceTypeRepository">设备类型仓储接口</param>
    public class DeleteRangeDeviceTypeHandler(IBaseRespository<DeviceType> deviceTypeRepository) : IRequestHandler<DeleteRangeDeviceTypeCommand, ApiResult<int>>
    {
        private readonly IBaseRespository<DeviceType> _deviceTypeRepository = deviceTypeRepository;

        /// <summary>
        /// 处理删除设备类型命令
        /// </summary>
        /// <param name="request">删除设备类型命令请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>包含操作结果的ApiResult</returns>
        public async Task<ApiResult<int>> Handle(DeleteRangeDeviceTypeCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 根据ID获取设备类型数据
                 var deviceTypes = await _deviceTypeRepository.GetRangeAsync(request.Ids);
                if (deviceTypes.Count == 0)
                {
                    return new ApiResult<int>
                    {
                        Msg = "未找到指定的设备类型",
                        Code = ApiEnum.Failed
                    };
                }

                // 执行批量软删除
                foreach (var deviceType in deviceTypes)
                {
                    deviceType.Isdel = true;
                }
                await _deviceTypeRepository.UpdateRange(deviceTypes);

                // 返回成功结果
                return new ApiResult<int>
                {
                    Code = ApiEnum.Success,
                    Msg = "批量删除成功",
                    Data = deviceTypes.Count
                };
            }
            catch (Exception ex)
            {
                // 异常时返回错误信息
                return new ApiResult<int>
                {
                    Code = ApiEnum.Failed,
                    Msg = $"删除设备类型时发生错误: {ex.Message}"
                };
            }
        }
    }
}